package com.jjclub.mapper.util;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @Classname BatchMapper
 * @Description TODO
 * @Date 2019/11/20 10:18
 * @Created by jq
 */
@Component
public class BatchMapper {
    @Autowired
    SqlSessionFactory sqlSessionFactory;


    @Transactional
    public void insertBatch(List dbList,Class t) {
        SqlSession   batchSqlSession= null;
        try {
            batchSqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
            int batchCount = 100;
            int batchLastIndex = batchCount;
            //创建代理对象
            Object instance = Proxy.newProxyInstance(
                    t.getClassLoader(),
                    new Class[]{t},
                    new MyInvocationHandler(batchSqlSession.getMapper(t))
            );
            Method method = instance.getClass().getMethod("insertBatch",List.class);

            if(dbList.size() > 100) {
                for (int index = 0; index < dbList.size();) {
                    if(batchLastIndex > dbList.size()){
                        method.invoke(instance,dbList.subList(index, dbList.size()));
                        batchSqlSession.commit();
                        System.out.println("index:" + index+ " batchLastIndex:" + batchLastIndex);
                        break;// 数据插入完毕，退出循环
                    }else {
                        method.invoke(instance,dbList.subList(index, batchLastIndex));
                        batchSqlSession.commit();
                        System.out.println("index:" + index+ " batchLastIndex:" + batchLastIndex);
                        index = batchLastIndex;
                        batchLastIndex = index + (batchCount - 1);
                    }
                }
                batchSqlSession.commit();
            }else {
                method.invoke(instance,dbList);
                batchSqlSession.commit();
            }
        } catch (Exception e) {
            batchSqlSession.rollback();
        }finally {
            batchSqlSession.close();
        }
    }

}
